import * as vscode from 'vscode';
import GlobalData from './GlobalData';
import * as jsonpath from "jsonpath"


class Provider implements vscode.CompletionItemProvider {

    private varPatern = /\$\{(.*)/g


    provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext) {
        const line = document.lineAt(position);

        // 只截取到光标位置为止，防止一些特殊情况
        // 取到$符号的位置
        let lineText = line.text.substring(0, position.character);
        lineText = lineText.substring(lineText.lastIndexOf("$"));
        // 简单匹配，只要当前光标前的字符串为`this.dependencies.`都自动带出所有的依赖
        if (this.varPatern.test(lineText)) {
            this.varPatern.lastIndex = 0
            const varPathRaw = this.varPatern.exec(lineText)![1]
            let varPath = "$"
            if (varPathRaw.lastIndexOf(".") != -1) {
                varPath = varPath + "." + varPathRaw.substring(0, varPathRaw.lastIndexOf("."))
            } else {
                varPath += "._root"
            }

            let data = jsonpath.query(GlobalData.Instance().VariaablesKeys(document), varPath)
            if (data) {
                return data[0]
            } else {
                return []
            }
        }
    }

}



export default function (context: vscode.ExtensionContext): void {
    context.subscriptions.push(vscode.languages.registerCompletionItemProvider("markdown", new Provider()))

    context.subscriptions.push(vscode.commands.registerCommand("yss-markdown.ReloadVar", () => {
        GlobalData.Instance().loadVar();
    }))
}